﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Historia.Formulaires;

namespace Historia
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Membres

        DataManager _dm = null;

        #endregion

        #region Constructeurs

        public MainWindow()
        {
            InitializeComponent();
            
            string[] args = Environment.GetCommandLineArgs();
            if ((args.Count() == 2) && (!string.IsNullOrEmpty(args[1]))) {
            	this.OuvrirProjet(args[1]);
             }
        }

        #endregion

        #region Propriétés

        public bool IsProjetOpened {
            get { return (this._dm != null) && (this._dm.DB != null); }
        }
        #endregion

        #region Méthodes

        /// <summary>
        /// Procédure qui applique la sécurité aux menus
        /// </summary>
        protected void ApplySecurity() {
            this.mnuInformationProjet.IsEnabled = this.IsProjetOpened;
            this.mnuPersonnages.IsEnabled = this.IsProjetOpened;
            this.mnuLieux.IsEnabled = this.IsProjetOpened;
            this.mnuItems.IsEnabled = this.IsProjetOpened;
            this.mnuRecherches.IsEnabled = this.IsProjetOpened;
            this.mnuFils.IsEnabled = this.IsProjetOpened;
            this.mnuOuvertRecemment.IsEnabled = this.mnuOuvertRecemment.HasItems;
        }

        /// <summary>
        /// Procédure qui créer un nouveau projet
        /// </summary>
        protected void NouveauProjet() {
            // Configure save file dialog box
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.DefaultExt = ".hst"; // Default file extension
            dlg.FileName = "Document";
            dlg.Filter = "Historia documents |*.hst|All files|*.*"; // Filter files by extension

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {

                // Crée le document
                this._dm = new DataManager(dlg.FileName);
                this._dm.CreerNouveauFichier();

                // Update window title
                this.UpdateTitle();

                // Show the main grid
                this.grdMain.Visibility = System.Windows.Visibility.Visible;

                //Initialise le contrôle de chapitre
                this.ctrlChapitres.Init(ref this._dm);

                //Initialise le contrôle Élément
                this.ctrElements.Init(ref this._dm);
            }

            // Applys the security on the form
            this.ApplySecurity();
        }

        /// <summary>
        /// Procédure qui ouvre un projet existant
        /// </summary>
        protected void OuvrirProjet(string fileName = null) {
            Nullable<bool> result = null;
            Microsoft.Win32.OpenFileDialog dlg = null;

            if (string.IsNullOrEmpty(fileName))
            {
                // Configure save file dialog box
            dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".hst"; // Default file extension
            dlg.Filter = "Historia documents |*.hst|All files|*.*"; // Filter files by extension

            // Show open file dialog box
             result = dlg.ShowDialog();
             fileName = dlg.FileName;
            }
            

            // Process open file dialog box results
            if ((result == true) || (!string.IsNullOrEmpty(fileName)))
            {
                // Open document
                this._dm = new DataManager(fileName);
                this._dm.OuvrirFichier(fileName);

                this.UpdateTitle();

                // Show the main grid
                this.grdMain.Visibility = System.Windows.Visibility.Visible;

                //Initialise le contrôle de chapitre
                this.ctrlChapitres.Init(ref this._dm);  
             
                //Initialise le contrôle Élément
                this.ctrElements.Init(ref this._dm);

                //Update la liste des fichiers ouvert récemment
                this.UpdateOpenRecentlyMenu(fileName);
            }

            // Applys the security on the form
            this.ApplySecurity();
        }

        /// <summary>
        /// Procédure qui maj le titre de la fenêtre
        /// </summary>
        protected void UpdateTitle() {
            // Update window title
            var query = from prj in this._dm.DB.Tables[DataManager.PROJET].AsEnumerable()
                        where prj.Field<Int32>("id_projet") == 1
                        select new { titreProjet = prj.Field<string>("titre") };

            this.Title = "Historia - " + query.First().titreProjet;
        }

        /// <summary>
        /// Fonction qui enregistre le fichier sous un autre nom
        /// </summary>
        /// <returns></returns>
        protected bool EnregistrerSous() {
            //
            //TODO: Copier la structure de répertoire
            //

            // Configure save file dialog box
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            if (string.IsNullOrEmpty(this._dm.NomFichier))
            {
                dlg.FileName = this._dm.DB.Tables[DataManager.PROJET].Rows[0].Field<string>("titre");
            }
            else {
                dlg.FileName = this._dm.NomFichier.Substring(this._dm.NomFichier.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1); // Default file name
            }
            dlg.DefaultExt = ".hst"; // Default file extension
            dlg.Filter = "Historia documents (.hst)|*.hst"; // Filter files by extension

            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                //Update le menu Ouvert Récemment
                this.UpdateOpenRecentlyMenu(dlg.FileName);

                // Save document
                return this._dm.Enregistrer(dlg.FileName);
            }

            return false;
        }

        protected void AssignElement(AssignElementRoutedEventArgs e) {
            DataRow dr = (DataRow)e.Element.Tag;
            DataRow drScene = (DataRow)ctrlChapitres.TreeViewItemScene.Tag;
            DataRow[] drAssigns = null;
            if (!(ctrlChapitres.TreeViewItemScene == null))
            {
                switch (e.ElementType)
                {
                    case AssignElementRoutedEventArgs.AssignElementTypeEnum.Personnage:
                         drAssigns = this._dm.DB.Tables[DataManager.PERSONNAGES_SCENES].Select("id_scene = " + drScene.Field<Int32>("id_scene").ToString() + " AND id_personnage = " + dr.Field<Int32>("id_personnage").ToString());
                        if (drAssigns.Length > 0)
                        {
                            foreach (DataRow drToDelete in drAssigns)
                            {
                                drToDelete.Delete();
                            }
                        }
                        else {
                            DataRow drAssign = this._dm.DB.Tables[DataManager.PERSONNAGES_SCENES].NewRow();
                            drAssign.SetField<Int32>("id_personnage", dr.Field<Int32>("id_personnage"));
                            drAssign.SetField<Int32>("id_scene", drScene.Field<Int32>("id_scene"));
                            this._dm.DB.Tables[DataManager.PERSONNAGES_SCENES].Rows.Add(drAssign);
                        }
                        break;
                    case AssignElementRoutedEventArgs.AssignElementTypeEnum.Lieu:
                         drAssigns = this._dm.DB.Tables[DataManager.LIEUX_SCENES].Select("id_scene = " + drScene.Field<Int32>("id_scene").ToString() + " AND id_lieu = " + dr.Field<Int32>("id_lieu").ToString());
                        if (drAssigns.Length > 0)
                        {
                            foreach (DataRow drToDelete in drAssigns)
                            {
                                drToDelete.Delete();
                            }
                        }
                        else {
                            DataRow drAssign = this._dm.DB.Tables[DataManager.LIEUX_SCENES].NewRow();
                            drAssign.SetField<Int32>("id_lieu", dr.Field<Int32>("id_lieu"));
                            drAssign.SetField<Int32>("id_scene", drScene.Field<Int32>("id_scene"));
                            this._dm.DB.Tables[DataManager.LIEUX_SCENES].Rows.Add(drAssign);
                        }
                        break;
                    case AssignElementRoutedEventArgs.AssignElementTypeEnum.Item:
                        drAssigns = this._dm.DB.Tables[DataManager.ITEMS_SCENES].Select("id_scene = " + drScene.Field<Int32>("id_scene").ToString() + " AND id_item = " + dr.Field<Int32>("id_item").ToString());
                        if (drAssigns.Length > 0)
                        {
                            foreach (DataRow drToDelete in drAssigns)
                            {
                                drToDelete.Delete();
                            }
                        }
                        else {
                            DataRow drAssign = this._dm.DB.Tables[DataManager.ITEMS_SCENES].NewRow();
                            drAssign.SetField<Int32>("id_item", dr.Field<Int32>("id_item"));
                            drAssign.SetField<Int32>("id_scene", drScene.Field<Int32>("id_scene"));
                            this._dm.DB.Tables[DataManager.ITEMS_SCENES].Rows.Add(drAssign);
                        }
                        break;
                    case AssignElementRoutedEventArgs.AssignElementTypeEnum.Fil:
                        drAssigns = this._dm.DB.Tables[DataManager.FILS_SCENES].Select("id_scene = " + drScene.Field<Int32>("id_scene").ToString() + " AND id_fil = " + dr.Field<Int32>("id_fil").ToString());
                        if (drAssigns.Length > 0)
                        {
                            foreach (DataRow drToDelete in drAssigns)
                            {
                                drToDelete.Delete();
                            }
                        }
                        else {
                            DataRow drAssign = this._dm.DB.Tables[DataManager.FILS_SCENES].NewRow();
                            drAssign.SetField<Int32>("id_fil", dr.Field<Int32>("id_fil"));
                            drAssign.SetField<Int32>("id_scene", drScene.Field<Int32>("id_scene"));
                            this._dm.DB.Tables[DataManager.FILS_SCENES].Rows.Add(drAssign);
                        }
                        break;
                    default:
                        break;
                }
                

                this.ctrlTexte.AfficherScene();
            }
        }

        protected void CreateOpenRecentlyMenu() {
            MenuItem menu = null;

            if (!string.IsNullOrEmpty(Properties.Settings.Default.LastOpen1))
	        {
                menu = new MenuItem();
                menu.Header = Properties.Settings.Default.LastOpen1;
                menu.Click +=new RoutedEventHandler(mnuOuvertRecemment_Click);
                this.mnuOuvertRecemment.Items.Add(menu);
	        }

            if (!string.IsNullOrEmpty(Properties.Settings.Default.LastOpen2))
            {
                menu = new MenuItem();
                menu.Header = Properties.Settings.Default.LastOpen2;
                menu.Click += new RoutedEventHandler(mnuOuvertRecemment_Click);
                this.mnuOuvertRecemment.Items.Add(menu);
            }

            if (!string.IsNullOrEmpty(Properties.Settings.Default.LastOpen3))
            {
                menu = new MenuItem();
                menu.Header = Properties.Settings.Default.LastOpen3;
                menu.Click += new RoutedEventHandler(mnuOuvertRecemment_Click);
                this.mnuOuvertRecemment.Items.Add(menu);
            }

            if (!string.IsNullOrEmpty(Properties.Settings.Default.LastOpen4))
            {
                menu = new MenuItem();
                menu.Header = Properties.Settings.Default.LastOpen4;
                menu.Click += new RoutedEventHandler(mnuOuvertRecemment_Click);
                this.mnuOuvertRecemment.Items.Add(menu);
            }

            if (!string.IsNullOrEmpty(Properties.Settings.Default.LastOpen5))
            {
                menu = new MenuItem();
                menu.Header = Properties.Settings.Default.LastOpen5;
                menu.Click += new RoutedEventHandler(mnuOuvertRecemment_Click);
                this.mnuOuvertRecemment.Items.Add(menu);
            }
        
        }

        protected void UpdateOpenRecentlyMenu(string fileName) {
            int index;
            List<string> lastOpenFiles = new List<string>();
            lastOpenFiles.Add(Properties.Settings.Default.LastOpen1);
            lastOpenFiles.Add(Properties.Settings.Default.LastOpen2);
            lastOpenFiles.Add(Properties.Settings.Default.LastOpen3);
            lastOpenFiles.Add(Properties.Settings.Default.LastOpen4);
            lastOpenFiles.Add(Properties.Settings.Default.LastOpen5);

            if (lastOpenFiles.Contains(fileName))
            {
                index = lastOpenFiles.IndexOf(fileName);
            }
            else
            {
                index = 4;
            }

            for (int i = index; i > 0; i--)
            {
                for (int y = index-1; y >= 0; y--)
                {
                    lastOpenFiles[i] = lastOpenFiles[y];
                }
            }

            Properties.Settings.Default.LastOpen5 = lastOpenFiles[4];
            Properties.Settings.Default.LastOpen4 = lastOpenFiles[3];
            Properties.Settings.Default.LastOpen3 = lastOpenFiles[2];
            Properties.Settings.Default.LastOpen2 = lastOpenFiles[1];
            Properties.Settings.Default.LastOpen1 = fileName;
            Properties.Settings.Default.Save();
            
        }

        #endregion

        private void mnuQuitter_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void NewCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                this.NouveauProjet();
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        private void OpenCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                this.OuvrirProjet();
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this._dm.NomFichier))
                {
                    this.EnregistrerSous();
                }
                else {
                    this._dm.Enregistrer(this._dm.NomFichier);
                }
                
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        private void SaveAsCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                this.EnregistrerSous();
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void mnuProjet_Click(object sender, RoutedEventArgs e)
        {
            frmProjet frm = new frmProjet();
            frm.Owner = this;
            if (frm.ShowFormDialog(ref this._dm).Value == true) {
                this.UpdateTitle();
            }
        }

        private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            try
            {
                e.CanExecute = this.IsProjetOpened;
            }
            catch (Exception)
            {
                e.CanExecute = false;
            }
            
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                this.CreateOpenRecentlyMenu();
                this.ApplySecurity();
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        private void mnuNouveauPersonnage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                frmPersonnage frm = new frmPersonnage();
                frm.Owner = this;
                frm.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                frm.ShowFormDialog(ref this._dm, null);

                //Rafraichit les éléments
                this.ctrElements.DisplayData();

            }
            catch (Exception)
            {
                
                throw;
            }
        }

        private void mnuGererPersonnages_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                frmListePersonnages frm = new frmListePersonnages();
                frm.Owner = this;
                frm.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                frm.ShowFormDialog(ref this._dm);

                //Rafraichit les éléments
                this.ctrElements.DisplayData();

            }
            catch (Exception)
            {

                throw;
            }
        }

        private void mnuNouveauLieu_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                frmLieu frm = new frmLieu();
                frm.Owner = this;
                frm.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                frm.ShowFormDialog(ref this._dm, null);

                //Rafraichit les éléments
                this.ctrElements.DisplayData();
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        private void mnuGererLieux_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                frmListeLieux frm = new frmListeLieux();
                frm.Owner = this;
                frm.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                frm.ShowFormDialog(ref this._dm);

                //Rafraichit les éléments
                this.ctrElements.DisplayData();
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        private void mnuNouvelItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                frmItem frm = new frmItem();
                frm.Owner = this;
                frm.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                frm.ShowFormDialog(ref this._dm, null);

                //Rafraichit les éléments
                this.ctrElements.DisplayData();
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        private void mnuGererItems_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                frmListeItems frm = new frmListeItems();
                frm.Owner = this;
                frm.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                frm.ShowFormDialog(ref this._dm);

                //Rafraichit les éléments
                this.ctrElements.DisplayData();
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        private void mnuNouvelleRecherche_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                frmRecherche frm = new frmRecherche();
                frm.Owner = this;
                frm.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                frm.ShowFormDialog(ref this._dm, null);

                //Rafraichit les éléments
                this.ctrElements.DisplayData();
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        private void mnuGererRecherches_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                frmListeRecherches frm = new frmListeRecherches();
                frm.Owner = this;
                frm.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                frm.ShowFormDialog(ref this._dm);

                //Rafraichit les éléments
                this.ctrElements.DisplayData();
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        private void mnuNouveauFil_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                frmFil frm = new frmFil();
                frm.Owner = this;
                frm.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                frm.ShowFormDialog(ref this._dm, null);

                //Rafraichit les éléments
                this.ctrElements.DisplayData();
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void mnuGererFils_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                frmListeFils frm = new frmListeFils();
                frm.Owner = this;
                frm.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                frm.ShowFormDialog(ref this._dm);

                //Rafraichit les éléments
                this.ctrElements.DisplayData();
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void ctrlChapitres_SelectionChanged(object sender, RoutedEventArgs e)
        {
            this.ctrlTexte.Chapitre = this.ctrlChapitres.TreeViewItemChapitre;
            this.ctrlTexte.Scene = this.ctrlChapitres.TreeViewItemScene;

            if (ctrlTexte.Chapitre == null)
            {
                this.ctrlTexte.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                this.ctrlTexte.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void ctrElements_AssignElementClick(object sender, RoutedEventArgs e)
        {
            try
            {
                this.AssignElement((AssignElementRoutedEventArgs)e);    
            }
            catch (Exception ex)
            {
                
                throw;
            }
        }

        private void mnuOuvertRecemment_Click(object sender, RoutedEventArgs e)
        {
            this.OuvrirProjet(((MenuItem)sender).Header.ToString());
        }

        private void mnuAbout_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                frmAbout frm = new frmAbout();
                frm.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                
                throw;
            }
        }

        private void mnuOptions_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                frmOptions frm = new frmOptions();
                frm.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                frm.ShowDialog();

                this.ctrlTexte.UpdateTextboxFont();
            }
            catch (Exception ex)
            {

                throw;
            }
        }

    }
}
